package net.binarism.journal
{
	import flash.events.Event;
	import flash.filesystem.*;
	
	import mx.events.*;
	import mx.formatters.DateFormatter;
	
	import spark.components.TextArea;
	
	public class EntryManager
	{
		private var _journalLocation:File;
		private var _currentFile:File;
		private var _prefs:PreferencesManager;
		private var _textArea:TextArea;
		private var stream:FileStream = new FileStream();
		
		
		public function EntryManager(textArea:TextArea)
		{
			_textArea = textArea;
			_prefs = new PreferencesManager();
			if(_prefs.getPreference(PreferencesManager.JOURNAL_LOCATION)){
				_journalLocation = new File(_prefs.getPreference(PreferencesManager.JOURNAL_LOCATION) as String);
			}
			
			if(!_journalLocation){
				//If there's no journal location in prefs get one from the user
				setJournalLocation();	
			}
			else{
				loadTodaysFile();
			}
		}
		
		
		/**
		 * Saves the given text to the current file.
		 */
		public function save(text:String):void{
			stream.open(getTodaysFile(), FileMode.WRITE);
			text = text.replace(/\r/g, File.lineEnding);
			stream.writeUTFBytes(text);
			stream.close();
		}


		/**
		 * Gets the file for today.
		 */ 
		private function getTodaysFile():File{
			var newFileFullPath:String = _journalLocation.nativePath + File.separator + EntryManager.getTodaysFileName()
			var todaysFile:File = new File(newFileFullPath);
			return todaysFile;
		}
		
		
		/**
		 * Gets the name of todays file.
		 */
		private static function getTodaysFileName():String{
			var dateFormatter:DateFormatter = new DateFormatter();
			dateFormatter.formatString = "YYYY-MM-DD";
			var fileName:String = dateFormatter.format(new Date()) + ".txt";
			return fileName;
		}
		
		
		/**
		 * Requests a journal location from the user.
		 */
		public function setJournalLocation():void{
			var newJournalLocation:File;
			if (_journalLocation){
				newJournalLocation = _journalLocation;
			}
			else{
				newJournalLocation = File.documentsDirectory;
			}
			newJournalLocation.browseForDirectory("Please select the location for your journal.");
			newJournalLocation.addEventListener(Event.SELECT, journalLocationSelected);
			newJournalLocation.addEventListener(Event.CANCEL, journalLocationNotSelected);
		}
		
		
		public function activate(lastActivated:Date):void{
			//TODO if yesterday & greater than a hour ago, bring up a new one.
			var now:Date = new Date();
			if(lastActivated.day != now.day){
				_textArea.text = "";
				loadTodaysFile();
			}
		}
		
		
		/**
		 * Loads todays file into the textArea.
		 */
		private function loadTodaysFile():void 
		{
			_currentFile = getTodaysFile();
			
			if(_currentFile.exists){
				stream.openAsync(_currentFile, FileMode.READ);
				stream.addEventListener(Event.COMPLETE, fileReadHandler);
			}
		}
	
		
		private function fileReadHandler(event:Event):void 
		{
			_textArea.text = stream.readUTFBytes(stream.bytesAvailable);
			stream.close();
		}
		
		
		private function journalLocationSelected(event:Event):void{
			_journalLocation = event.target as File;
			_currentFile = getTodaysFile();
			_prefs.setPreference(PreferencesManager.JOURNAL_LOCATION, _journalLocation.nativePath);
			_prefs.savePreferences();
		}
		
		
		private function journalLocationNotSelected(event:Event):void{
			if(!_journalLocation){
				//TODO fire alert to grey the box out, show alert.
			}
		}
	}
}